package main

import (
	"bufio"
	"fmt"
	"io"
	"myfunction"
	"mystruct"
)

//闭包函数
func Add() func(int) int {
	sum := 0
	return func(v int) int {
		sum += v
		return sum
	}
}
func main() {
	a := Add() //a所指向的函数中包裹了一个变量sum，a函数被多次调用但sum变量的声明周期一直持续
	for i := 1; i <= 10; i++ {
		fmt.Println("a(", i, "):", a(i))
	}
	fmt.Println("a(5):", a(5)) // 60

	b := Add() //b是另一个新开辟的函数，一个新函数自然函数中的sum变量也是重新初始化的
	for i := 1; i <= 10; i++ {
		fmt.Println("b(", i, "):", b(i))
	}
	fmt.Println("b(10):", b(10)) // 65

	fmt.Println("a(7):", a(7)) // 65

	fmt.Println()
	fmt.Println("斐波那契数列:")
	fibonacci := myfunction.Fibonacci()
	for i := 0; i <= 30; i++ {
		fmt.Printf("%v ", fibonacci())
	}
	///////////////////////////
	///////////////////////////

	fmt.Println()
	fmt.Println("自定义类型:")
	fibonacci2 := myfunction.Fibonacci2()
	printFileContents(fibonacci2)
	///////////////////////////
	///////////////////////////

	root := mystruct.TreeNode{Value: 3}
	root.Left = &mystruct.TreeNode{}
	//fmt.Println("root's left:", root.Left)
	root.Left.SetTreeNodeValue(100)
	//fmt.Println("root's left:", root.Left)
	root.Left.SetTreeNodeValue2(100)
	//fmt.Println("root's left:", root.Left)

	root.Right = &mystruct.TreeNode{5, nil, nil}
	//fmt.Println("root's right:", root.Right)

	root.Right.Left = new(mystruct.TreeNode)
	//fmt.Println("root's right's left:", root.Right.Left)

	root.Left.Right = mystruct.InitTreeNode(2)
	//fmt.Println("root's left's right:", root.Left.Right)

	//原遍历功能
	fmt.Println()
	fmt.Println("原遍历打印功能:")
	root.Traversing()
	fmt.Println("新遍历打印功能:")
	//传入的函数是打印，则执行打印的功能
	root.TraversingFunc(func(node *mystruct.TreeNode) {
		node.Print()
	})

	//传入的函数是计数，则执行计数的功能
	count := 0
	root.TraversingFunc(func(node *mystruct.TreeNode) {
		count++
	})
	fmt.Println("新遍历计数功能:")
	fmt.Println("count:", count)

}

func printFileContents(reader io.Reader) {
	scanner := bufio.NewScanner(reader)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
}
